/**
 * Created with IntelliJ IDEA.
 * Description:数据流中的第k大元素
 * User: YJ
 * Date: 2024-4-06
 * Time: 15:48
 */
public class KthLargestExe {

    private MinHeap minHeap;

    /**
     * 数据流中的第k大元素
     * @param arr
     * @param k
     * @return
     */
    public void kthLargest(int[] arr,int k) {
        //创建小顶堆
        minHeap = new MinHeap(k);
        for (int val : arr) {
            add(val);
        }
    }

    /**
     * 添加
     * @param val
     * @return
     */
    public int add(int val) {
        if (!minHeap.isFull()) {
            minHeap.offer(val);
        }else if (val > minHeap.peek()) {
            //替换
            minHeap.replace(val);
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        KthLargestExe test = new KthLargestExe();
        test.kthLargest(new int[]{4, 5, 8, 2}, 3);
        System.out.println(test.add(3));    //4
        System.out.println(test.add(5));    //5
        System.out.println(test.add(10));   //5
        System.out.println(test.add(9));    //8
        System.out.println(test.add(4));    //8
    }
}
